<template>
  <div>
    <div>
      <el-dialog :visible.sync="visible"
                 class="add_new_report"
                 :title="this.cloneDataInfo?$t('custom.report.clone'):(dataForm.id==='1338420673936867329'? `Add New ${reportDialogTitle}`:$t('custom.report.edit'))"
                 :close-on-click-modal="false"
                 :close-on-press-escape="false"
                 :append-to-body="true"
                 :modal='true'
                 @closed="clearFormData"
                 width="450px">
        <div v-loading="loading">
          <el-form :model="dataForm"
                   :rules="dataRule"
                   :inline="false"
                   ref="newReportDataForm"
                   @submit.native.prevent
                   @keyup.enter.native="dataFormSubmitHandle()"
                   label-width="80px"
                   label-position="top">
            <el-form-item>
              <div class="report_intor">
                {{
                  isTemplateClone ?
                  'In order to edit a widget/report template,it needs to be cloned to custom widget/report first that will show up in My Widgets/My tab. Do you want to proceed':
                  'Name your new custom dashboard and select the widgets to be used in the dashboard on the next page.'
                }}
              </div>
            </el-form-item>
            <el-form-item prop="name"
                          :label="$t('custom.reports.name')">
              <el-input v-model="dataForm.name"
                        maxlength="70"
                        :placeholder="$t('custom.reports.name')"></el-input>
            </el-form-item>
            <el-checkbox v-if="this.cloneDataInfo&&$hasPermission('sys:report:reportclonefortenant')" style="margin:10px 0"
                         v-model="clonewidget">{{$t('custom.reports.clonewidget')}}</el-checkbox>
            <el-form-item prop="roleIdList"
                          :label="$t('custom.reports.role')">
              <el-select v-model="dataForm.roleIdList"
                         filterable
                         clearable
                         multiple
                         default-first-option
                         :placeholder="$t('custom.reports.role')"
                         style="width: 100%;">
                <el-option v-for="(its,iii) in fullRoleList"
                           :key="iii"
                           :label="its.name"
                           :value="its.roleId"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="tagList"
                          :label="$t('custom.reports.tag')">
              <el-select v-model="dataForm.tagList"
                         filterable
                         clearable
                         multiple
                         allow-create
                         collapse-tags
                         default-first-option
                         :placeholder="$t('custom.reports.tag')"
                         style="width: 100%;">
                <el-option v-for="(its,iii) in tags"
                           :key="iii"
                           :label="its.name"
                           :value="its.name">
                           <div style="display: flex;justify-content:space-between;">
                             <ZTooltip :content="its.name"
                                :line="1"
                               placement="top">
                                 <span style="flex:1">{{ its.name }}</span>
                             </ZTooltip>
                             <span>
                               <el-button 
                                            style="float: right;font-size: 14px;margin-top: 3px;margin-left: 10px;"
                                            size='mini'
                                            type="text"
                                            @click.stop="deleteTag(its)">
                                   <i class="cuifont icon_delete"
                                      style="font-size:14px;color:#CCC"></i>
                                 </el-button>
                             </span>
                            </div>
                          </el-option>
              </el-select>
            </el-form-item>
            <!-- <el-form-item prop="layoutType" label="Layout Type">
                 <el-select v-model="dataForm.layoutType"
                         clearable
                         default-first-option
                         placeholder="Please Select Layout Type"
                         style="width: 100%;">
                <el-option label="Report"
                           value="report_layout"></el-option>
                    <el-option label="Scorecard"
                           value="scorecard_layout"></el-option>
              </el-select>
            </el-form-item> -->
            <el-form-item prop="description"
                          :label="$t('custom.reports.description')">
              <el-input v-model="dataForm.description"
                        @keyup.enter.native.stop
                        v-if="visible"
                        maxlength="500"
                        type="textarea"
                        rows="3"
                        :placeholder="$t('custom.reports.description')"></el-input>
            </el-form-item>
            <el-form-item prop="theme"
                  v-if="dataForm.layoutType==='report_layout'&&!this.cloneDataInfo"
                  :label="$t('custom.reports.theme')">
              <div class="flex" style="width:100%">
                <div :key="index"
                    v-for="(item,index) in themeList"
                    @click="dataForm.theme=item.label"
                    style="position:relative;width:110px;height:80px;marginRight:10px;cursor:pointer"
                    :style="{border:dataForm.theme===item.label?'1px solid #45c2b5':''}">
                    <el-image
                      style="position:absolute;width:20px;height:20px;top:5px;right:5px;z-index:9"
                      v-show="dataForm.theme===item.label"
                      :src="require('@/assets/img/yes.png')">
                    </el-image>
                  <el-image
                      style="width: 100%; height: 100%; "
                      :src="item.url">
                  </el-image>
                </div>
              </div>
            </el-form-item>
            <!-- <el-form-item label="Picture"
                          v-if="dataForm.id">
              <ZHighUpload v-model="filePath"
                           :id="dataForm.id"
                           :resourceType="0"
                           :file-list="getSnapshot"
                           :after-upload="depositSnapshot" />
            </el-form-item> -->

            <!-- <ClientSelect v-if="clonewidget" ref="ClientSelect" style="margin:10px 0 20px" ></ClientSelect> -->
            <el-form-item>
              <el-button type="primary"
                         size="small"
                         style="float:right"
                         @click="dataFormSubmitHandle()">{{ $t('custom.reports.continue') }}</el-button>
              <el-button type="text"
                         style="float:right;margin-right:10px"
                         v-if="($hasPermission('sys:report:moreedit')&&!this.cloneDataInfo) || $store.state.user.username.includes('mspbots.ai')"
                         @click="reportMoreEdit"
                         size="small">{{ $t('custom.reports.moreedit') }}</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>
    </div>
    <el-dialog :visible.sync="moreEditVisible"
               :title="$t('custom.reports.moreedit')"
               :append-to-body="true"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :modal='false'
               width="470px">
      <div v-loading="loading">
        <div class="screen-y scroll-css more-edit-dialog"
           style="height:400px;">
        <el-form :model="dataForm"
                 ref="dataForm"
                 @submit.native.prevent
                 @keyup.enter.native="dataFormSubmitHandle()"
                 label-position="top">
          <el-row :gutter="23">
            <el-col :span="11">
              <el-form-item prop="businessType"
                            :label="$t('custom.dataset.businessType')">
                <el-select v-model="dataForm.businessType"
                           :placeholder="$t('custom.dataset.businessType')"
                           style="width: 100%;"
                           :disabled="!$hasPermission('sys:tenant:model:allowtomanagesystemmodel')">
                  <el-option v-for="its in businessTypeList"
                             :key="its.dictValue"
                             :label="its.dictLabel"
                             :value="its.dictValue"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item prop="status"
                            :label="$t('custom.dataset.status')"
                            class="right-margin">
                <el-select v-model="dataForm.status"
                           :placeholder="$t('custom.dataset.status')"
                           style="width: 100%;"
                           :disabled="!$hasPermission('sys:tenant:model:allowtomanagesystemmodel')">
                  <el-option v-for="its in statusList"
                             :key="its.dictValue"
                             :label="its.dictLabel"
                             :value="its.dictValue"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item prop="tenantCode"
                            :label="$t('custom.dataset.tenantCode')">
                <select-client-id v-model="dataForm.tenantCode"
                                  :disabled="dataForm.businessType==='Template' || dataForm.businessType==='MSPbots Internal'"
                                  :width="100"></select-client-id>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item prop="da"
                            :label="$t('custom.report.da')"
                            class="right-margin">
                <el-select v-model="dataForm.da"
                           clearable
                           filterable
                           :placeholder="$t('custom.report.da')"
                           style="width: 100%;">
                  <el-option v-for="its in userList"
                             :key="its.id"
                             :label="its.realname"
                             :value="its.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item prop="po"
                            :label="$t('custom.report.po')">
                <el-select v-model="dataForm.po"
                           clearable
                           filterable
                           :placeholder="$t('custom.report.po')"
                           style="width: 100%;">
                  <el-option v-for="its in userList"
                             :key="its.id"
                             :label="its.realname"
                             :value="its.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item prop="jiraNumber"
                            class="right-margin"
                            :label="$t('custom.reports.jiraNumber')">
                <el-input v-model="dataForm.jiraNumber"
                          @keyup.enter.native.stop
                          type="text"
                          style="width: 100%"
                          rows="3"
                          :placeholder="$t('custom.reports.jiraNumber')">
                  <JiraNumberLink slot="suffix"
                                  :jiraNumber="dataForm.jiraNumber" />
                </el-input>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="11">
              <el-form-item prop="teamId"
                            :label="$t('custom.dataset.team')">
                <select-team-id v-model="dataForm.teamId"
                                :width="100"></select-team-id>
              </el-form-item>
            </el-col> -->
            <el-col :span="22">
              <el-form-item prop="progress"
                            :label="$t('custom.reports.progress')">
                <el-input v-model="dataForm.progress"
                          :placeholder="$t('custom.reports.progress')"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item prop="eta"
                            :label="$t('custom.reports.eta')">
                <!-- <el-input v-model="dataForm.eta"
                        :placeholder="$t('custom.reports.eta')"></el-input> -->
                <el-date-picker v-model="dataForm.eta"
                                type="date"
                                style="width: 100%;"
                                :label="$t('custom.reports.eta')">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item prop="priority"
                            :label="$t('custom.reports.priority')"
                            class="right-margin">
                <el-select v-model="dataForm.priority"
                           :placeholder="$t('custom.reports.priority')"
                           :disabled='false'
                           style="width: 100%;">
                  <el-option label="High"
                             value="High"></el-option>
                  <el-option label="Medium"
                             value="Medium"></el-option>
                  <el-option label="Low"
                             value="Low"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item prop="client"
                            :label="$t('custom.reports.client')">
                <el-input v-model="dataForm.client"
                          @keyup.enter.native.stop
                          type="textarea"
                          rows="2"
                          :placeholder="$t('custom.reports.client')"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item prop="uat"
                            :label="$t('custom.reports.uat')">
                <el-select v-model="dataForm.uat"
                           :disabled='false'
                           :placeholder="$t('custom.reports.uat')"
                           style="width: 100%;">
                  <el-option v-for="its in uatList"
                             :key="its.value"
                             :label="its.lable"
                             :value="its.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item prop="overheadFilters"
                            :label="$t('custom.reports.overheadFilters')"
                            class="right-margin">
                <el-select v-model="dataForm.overheadFilters"
                           :disabled='false'
                           :placeholder="$t('custom.reports.overheadFilters')"
                           style="width: 100%;">
                  <el-option v-for="its in optionList"
                             :key="its.value"
                             :label="its.lable"
                             :value="its.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item prop="reportingQa"
                            :label="$t('custom.reports.reportingQa')">
                <el-select v-model="dataForm.reportingQa"
                           :disabled='false'
                           :placeholder="$t('custom.reports.reportingQa')"
                           style="width: 100%;">
                  <el-option v-for="its in optionList"
                             :key="its.value"
                             :label="its.lable"
                             :value="its.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item prop="allClientsQa"
                            :label="$t('custom.reports.allClientsQa')"
                            class="right-margin">
                <el-select v-model="dataForm.allClientsQa"
                           :disabled='false'
                           :placeholder="$t('custom.reports.allClientsQa')"
                           style="width: 100%;">
                  <el-option v-for="its in optionList"
                             :key="its.value"
                             :label="its.lable"
                             :value="its.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item prop="internalNotes"
                            :label="$t('custom.reports.internalNotes')">
                <el-input v-model="dataForm.internalNotes"
                          @keyup.enter.native.stop
                          type="textarea"
                          rows="2"
                          :placeholder="$t('custom.reports.internalNotes')"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

        </el-form>
      </div>
      <div style="display:flex;justify-content: flex-end;margin-top:20px">
        <el-button @click="moreEditVisible = false"
                   size="small">{{ $t('Cancel') }}</el-button>
        <el-button type="primary"
                   size="small"
                   @click="dataFormSubmitHandle()">{{ $t('Save') }}</el-button>
      </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import qs from 'qs'
import { getUUID } from '@/utils'
import { isIncludeSymbol } from '@/utils/validate'
import JiraNumberLink, { JiraNumberMixin } from '@/components/jira-number-link'
import ClientSelect from './client-select.vue'
import Snapshot from '@/components/storybook/mixins/snapshot'
import ZHighUpload from '@/components/storybook/z-upload/src/z-high-upload'
import { cloneDeep } from 'lodash'
import ZTooltip from '@/components/storybook/z-tooltip'
import { deleteTag } from '@/api/new'
import bus from '@/components/storybook/utilties/bus'

export default {
  components: {
    JiraNumberLink,
    ClientSelect,
    ZHighUpload,
    ZTooltip
  },
  mixins: [JiraNumberMixin, Snapshot],
  props: {
    presentModeItem: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      assignRoleList: [],
      visible: false,
      moreEditVisible: false,
      loading: false,
      integrationList: [],
      dataForm: {
        id: null,
        name: null,
        integration: [],
        tagList: [],
        businessId: getUUID(),
        businessType: 'Custom',
        // language: 'sql', // sql,grovvy,json
        type: 1,
        // content: null,
        description: null,
        tenantCode: this.$store.state.user.tenantCode,
        status: !this.$hasPermission('sys:report:moreedit') ? 'Published' : 'Requested',
        da: '',
        po: '',
        jiraNumber: '',
        roleIdList: [],
        // about DA
        internalNotes: null,
        uat: null,
        overheadFilters: null,
        allClientsQa: null,
        reportingQa: null,
        priority: null,
        eta: null,
        client: null,
        progress: null,
        teamId: ''

      },
      filePath: undefined,
      clonewidget: false,
      cloneTenantCode: null,
      cloneDataInfo: null,
      userList: [],
      roleList: [],
      successStr: 'New successfully',
      optionList: [
        {
          value: 'Pending',
          label: 'Pending'
        },
        {
          value: 'In Progress',
          label: 'In Progress'
        }, {
          value: 'Waiting for Dev',
          label: 'Waiting for Dev'
        },
        {
          value: 'Done',
          label: 'Done'
        }],
      uatList: [
        {
          value: 'Pending',
          label: 'Pending'
        },
        {
          value: 'Awaiting Response',
          label: 'Awaiting Response'
        }, {
          value: 'With Feedback',
          label: 'With Feedback'
        },
        {
          value: 'Done',
          label: 'Done'
        }
      ],
      tags: [],
      originalForm: {},
      resourceName: '',
      resourcebusinessType: '',
      themeList:[]
    }
  },
  watch: {
    visible (val) {
      if (!val) {
        this.cloneDataInfo = null
        this.dataForm.status = null
        this.dataForm.businessType = null
        this.clearFormData()
        this.$root.eventBus.$emit('bus:tag-refresh')
      } else {

      }
    }
  },

  computed: {
    layoutTypeReport () {
      if (this.$route.path.includes('Scorecard')) {
        return 'scorecard_layout'
      }

      return 'report_layout'
    },
    reportDialogTitle () {
      if (this.$route.path.includes('Scorecard')) {
        return 'Scorecard Dashboard'
      }
      if (this.$route.path.includes('CrossTenant')) {
        return 'Internal Dashboard'
      }

      return 'Dashboard'
    },
    dataRule () {
      var validateSymbol = (rule, value, callback) => {
        if (!isIncludeSymbol(value)) {
          return callback()// callback(new Error(this.$t('validate.isIncludeSymbol')))
        }
        callback()
      }
      return {
        name: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur', pattern: '[^ \x22]+' },
          { validator: validateSymbol, trigger: 'blur' },
          { min: 0, max: 69, message: this.$t('custom.tips.valueLength', { length: '70' }), trigger: 'change' },
          { validator: this.validatePass, trigger: 'blur' }
        ],
        roleIdList: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        description: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' },
          { min: 0, max: 499, message: this.$t('custom.tips.valueLength', { length: '500' }), trigger: 'change' }
        ],
        layoutType: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        tenantCode: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    },
    businessTypeList () {
      try {
        if (this.dataForm.id) {
          if (this.$hasPermission('sys:report:type:mspbots internal') && this.dataForm.businessType === 'MSPbots Internal') {
            return window.SITE_CONFIG['dictList'].find(e => e.dictType === 'datasets_type_list').dataList.filter(item => {
              return item.dictValue === 'MSPbots Internal'
            })
          } else {
            return window.SITE_CONFIG['dictList'].find(e => e.dictType === 'datasets_type_list').dataList.filter(item => {
              return item.dictValue !== 'MSPbots Internal'
            })
          }
        } else {
          if (this.$hasPermission('sys:report:type:mspbots internal') && this.$route.path.includes('CrossTenant')) {
            return window.SITE_CONFIG['dictList'].find(e => e.dictType === 'datasets_type_list').dataList.filter(item => {
              return item.dictValue === 'MSPbots Internal'
            })
          } else {
            return window.SITE_CONFIG['dictList'].find(e => e.dictType === 'datasets_type_list').dataList.filter(item => {
              return item.dictValue !== 'MSPbots Internal'
            })
          }
        }
      } catch (error) {
        return []
      }
    },
    statusList () {
      try {
        var list = window.SITE_CONFIG['dictList'].find(e => e.dictType === 'datasets_status_list').dataList
        if (this.$hasPermission('sys:reports:publishauth')) {
          return list
        } else {
          return this._.reject(this._.reject(list, { dictValue: 'Alpha' }), { dictValue: 'Published' })
        }
      } catch (error) {
        return []
      }
    },
    fullRoleList () {
      let roleList = this.roleList
      let assignRoleList = this.assignRoleList
      let roleTemp = []
      let assignTemp = []
      let temp = []
      roleList.forEach(ii => {
        roleTemp.push({
          roleId: ii.roleId,
          name: ii.name
        })
      })
      assignRoleList.forEach(it => {
        assignTemp.push({
          roleId: it.assignId,
          name: ''
        })
      })
      temp = this._.intersectionBy(roleTemp, assignTemp, 'roleId')
      return temp
    },
    isTemplateClone () {
      return this.originalForm.businessType === 'Template' && this.cloneDataInfo && this.$route.path.indexOf('/dashboard-') !== -1 && !this.hasEditPermission
    },
    hasEditPermission () {
      let temp = false
      let reportadmin = this.$hasPermission('sys:report:reportadmin') ? 1 : 0
      let editAuth = this.$hasPermission('sys:report:edit') ? 1 : 0
      let isCustom = this.originalForm.businessType === 'Custom' ? 1 : 0
      if (reportadmin + editAuth + isCustom >= 2) {
        temp = true
      } else {
        temp = false
      }
      if (this.presentModeItem) {
        temp = false
      }
      return temp
    }
  },

  methods: {
    init () {
      this.visible = true
      if(!this.cloneDataInfo){
        const obj=window.SITE_CONFIG['themeList']
        this.themeList=[]
        Object.keys(obj).forEach(v=>{
          this.themeList.push({
            label:v,
            url:window.SITE_CONFIG['ossAddressURL']+obj[v].url
          })
        })
      }
      this.getUserList()
      Promise.all([
        this.getRoleList(),
        this.getAssignRoleList()
      ]).then(() => {
        this.$nextTick(() => {
          if (this.dataForm.id) {
            this.getInfo()
          } else {
            this.dataForm.businessId = getUUID()
          }
        })
      }).catch(() => {
        this.loading = false
      })
      this.getTags()
    },
    validatePass (rule, value, callback) {
      let params = {
        name: value.trim(),
        isNew: this.cloneDataInfo ? true : (this.dataForm.id === '1338420673936867329'),
        businessType: this.dataForm.businessType,
        tenantCode: this.dataForm.tenantCode ? this.dataForm.tenantCode : this.$store.state.user.tenantCode,
        layoutType: this.layoutTypeReport
      }
      if (params.isNew) {
        params.reportId = ''
      } else {
        params.reportId = this.dataForm.id
      }
      this.$interface.reports.postCheckNameApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return callback(new Error('The name is already exists'))
          }
          callback()
        })
    },
    cloneShow (rowData) {
      const { cloneDeep } = this._
      this.cloneDataInfo = cloneDeep(rowData)
      this.cloneDataInfo.tenantCode = this.$store.state.user.tenantCode
      this.cloneDataInfo.status = !this.$hasPermission('sys:report:moreedit') ? 'Published' : 'Requested'
      this.cloneDataInfo.businessType = rowData.businessType === 'MSPbots Internal' ? 'MSPbots Internal' : 'Custom'
      this.cloneDataInfo.roleIdList = this.$store.state.defaultRoleList.concat(['1539094477886771202','1603251831365554178'])
    },
    getInfo () {
      // this.loading = true
      this.$interface.reports.getReportsInfoApi(this.dataForm.id).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.originalForm = cloneDeep(res.data) || {}
        if (res.data.id === '1338420673936867329') {
          res.data.name = ''
          res.data.tenantCode = this.$store.state.user.tenantCode
        }
        if (this.cloneDataInfo) {
          res.data.roleIdList = this.$store.state.defaultRoleList.concat(['1539094477886771202','1603251831365554178'])
        }
        this.dataForm = res.data
        if (res.data.id === '1338420673936867329') {
          this.dataForm.da = this.$store.state.user.id
          this.dataForm.status = !this.$hasPermission('sys:report:moreedit') ? 'Published' : 'Requested'
          if (this.$route.path.includes('CrossTenant')) {
            this.dataForm.businessType = 'MSPbots Internal'
          } else {
            this.dataForm.businessType = 'Custom'
          }
        }
        this.resourceName = res.data.name
        this.resourcebusinessType = res.data.businessType
        if (!this.dataForm.teamId) {
          this.dataForm.teamId = ''
        }
        let roleList = []
        if (res.data.id === '1338420673936867329') {
          res.data.roleIdList = this.$store.state.defaultRoleList.concat(['1539094477886771202','1603251831365554178'])
        }
        for (var i = 0; i < res.data.roleIdList.length; i++) {
          if (this.fullRoleList.filter(item => item.roleId === res.data.roleIdList[i])[0]) {
            roleList.push(res.data.roleIdList[i])
            continue
          }
          // this.roleIdListDefault.push(res.data.roleIdList[i])
        }
        if (this.cloneDataInfo) {
          this.dataForm.status = 'Published'
          this.dataForm.businessType = this.cloneDataInfo.businessType === 'MSPbots Internal' ? 'MSPbots Internal' : 'Custom'
          this.dataForm.tenantCode = this.$store.state.user.tenantCode
        }

        if (this.isTemplateClone) {
          this.dataForm.name = `${this.dataForm.name} - clone`
        }
        this.$set(this.dataForm, 'roleIdList', roleList)
        this.dataForm.roleIdList = roleList
        this.dataForm.theme=this.dataForm.theme||'white'
        this.loading = false
      })
    },
    getlayoutType (type) {
      if (type === 'scorecard_layout') {
        return 'mspbots/reports/scorecard-layout'
      } else {
        return 'mspbots/reports/report-layout'
      }
    },
    addReportRouter (route) {
      this.changePages({
        id: route.id,
        name: 'report-' + route.name
      })

      if (this.isTemplateClone) {
        this.$store.state.rowData = route
        const { path } = this.$route
        if (path === '/Scorecards') {
          this.$router.push({
            path: `/scorecard-${route.id}`,
            query: {
              pageid: route.id,
              name: route.name
            }
          })
        } else {
          this.$router.push({
            path: `/dashboard-${route.id}`,
            query: {
              pageid: route.id,
              name: route.name
            }
          })
        }
      }
    },
    changePages (newParam) {
      this.$store.dispatch('routeMetaStor', {
        menuId: newParam.id,
        title: newParam.name
      })
    },
    reportMoreEdit () {
      this.moreEditVisible = true
    },
    async dataFormSubmitHandle () {
      this.loading = true
      const { set, get } = this._
      const dataForm = {
        ...this.dataForm
      }

      if (!get(dataForm, 'id') || get(dataForm, 'id') === '1338420673936867329') {
        set(dataForm, 'layoutType', this.layoutTypeReport)
      }
      if (this.$store.state.user.username.includes('mspbots.ai') && this.$hasPermission('sys:report:moreedit')) {
        if (!dataForm.da) {
          this.loading = false
          return this.$message.error(this.$t('custom.component.gadget.da'))
        }
        if (!dataForm.po) {
          this.loading = false
          return this.$message.error(this.$t('custom.component.gadget.po'))
        }

        const isMatchJiraNumber = await this.checkJiraNumber(dataForm.jiraNumber)

        if (!isMatchJiraNumber) {
          this.loading = false
          return this.$message.error(this.$t('custom.component.gadget.checkNumber'))
        }
      }

      if (this.cloneDataInfo) {
        if (this.resourceName === this.dataForm.name && this.resourcebusinessType === 'Template') {
        this.loading = false
        return this.$message.error('You cannot use the same name as a template dashboard. Please choose another name.')
      }
        if (dataForm.roleIdList.length <= 0) {
          this.loading = false
          return this.$message.error('Please Select Role')
        }
        this.cloneReport(this.cloneDataInfo, dataForm, true)
        this.moreEditVisible = false
        // this.visible = false
      } else {
        if (dataForm.tenantCode === '1001' && dataForm.businessType === 'Custom') {
          this.loading = false
          return this.$message.error('The login person is the default tenant, then the type of widget cannot be Custom.')
        }
        this.verifyForm()
          .then(() => {
            if (dataForm.description.match(/^[ ]*$/)) {
              return this.$message.error('Description ' + this.$t('validate.required'))
            }
            if (dataForm.id === '1338420673936867329') {
              this.cloneReport(dataForm, dataForm, true)
            } else {
              this.loading = true
              this.$interface.reports.putReportsApi(dataForm.id, dataForm).then(({ data: res }) => {
                if (res.code !== 0) {
                  this.loading = false
                  return this.$message.error(res.msg)
                }
                if (res.data.exist) {
                  this.loading = false
                  this.$message.error(this.$t('custom.dataset.nameexist'))
                } else {
                  this.moreEditVisible = false
                  this.visible = false
                  this.loading = false
                  this.addReportRouter(res.data)
                  this.$emit('refreshDataList')
                  this.$emit('refreshCardList')
                  return this.$message.success(res.msg)
                }
              })
            }
          })
          .catch(() => {
            this.loading = false
          })
      }
    },
    cloneReport (data, dataForm, addRoute) {
      if (this.clonewidget) {
        // reportId
        const params = {
          id: data.id,
          // tenantCode: this.$refs.ClientSelect.getTenantCode(),
          tenantCode: this.$store.state.user.tenantCode,
          name: dataForm.name
        }
        let _self = this
        if (data.id !== '1338420673936867329') _self.successStr = 'Clone Success'
        _self.loading = true
        // params.cloneInfoList = [{ gadgetType: 'pageheadergadget' }]
        _self.$interface.reports.cloneByTenantCodeApi(params).then(({ data: res }) => {
          if (res.code !== 0) {
            _self.loading = false
            return _self.$message.error(res.msg)
          }

          _self.$message.success(_self.successStr)
          _self.$emit('refreshDataList')
          _self.$emit('refreshCardList')
          this.$store.state.needRefreshDashboardList=true
          this.$store.state.needRefreshWidgetList=true
          _self.moreEditVisible = false
          _self.visible = false
          _self.loading = false
          // if (addRoute) {
          //   _self.addReportRouter(res.data)
          //   _self.$emit('routerAdd', res.data)
          // }
        }).catch(() => {
          _self.loading = false
          _self.$message.error('Internal Server Error')
        })
      } else {
        // reportId
        const params = {
          reportId: data.id,
          id: data.id,
          ...dataForm
        }
        let _self = this
        if (data.id !== '1338420673936867329') _self.successStr = 'Clone Success'
        _self.loading = true
        params.cloneInfoList = [{ gadgetType: 'pageheadergadget' }]
        _self.$interface.reports.cloneReportsApi(params).then(({ data: res }) => {
          if (res.code !== 0) {
            _self.loading = false
            return _self.$message.error(res.msg)
          }

          _self.$message.success(_self.successStr)
          _self.$emit('refreshDataList')
          _self.$emit('refreshCardList')
          this.$store.state.needRefreshDashboardList=true
          _self.moreEditVisible = false
          _self.visible = false
          _self.loading = false
          if (addRoute) {
            _self.addReportRouter(res.data)
            _self.$emit('routerAdd', res.data)
          }
        }).catch(() => {
          _self.loading = false
          _self.$message.error('Internal Server Error')
        })
      }
    },
    verifyForm () {
      return this.$refs['newReportDataForm'].validate()
    },
    getUserList () {
      const params = {
        datasetKey: 'qwerdsafsadrtfzgsadfggs'
      }
      this.$interface.reports.getDrillThroughDataInfo(params).then(({ data: res }) => {
        if (res.data) {
          this.userList = res.data
        }
      })
    },
    deleteTag(tag) {
      if (!tag) return false
      this.$confirm('Are you sure to delete?','warning', {
        type: 'warning',
      })
        .then(async () => {
          const params = {
            id: tag.id,
          }
          const { data: res } = await deleteTag(params)
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.dataForm.tagList = this.dataForm.tagList&&this.dataForm.tagList.filter(
            item => item!== tag.name
          )
          this.getTags()
          this.$message.success(res.msg)
          bus.$emit('update:tags', this.tags)
        })
    },
    async getTags () {
      try {
        const { tags } = this.$interface.reports
        const { get } = this._
        const params = {}

        const { data: response } = await tags(params)

        if (response.code !== 0) {
          throw get(response, 'msg', '')
        }

        this.tags = get(response, 'data', [])
      } catch (error) {

      } finally {

      }
    },
    async getRoleList () {
      this.loading = true
      const params = {
        tenantCode: this.$store.state.user.tenantCode
      }
      const { data: res } = await this.$interface.system.getClientRoleListApi(params)
      if (res.code !== 0) {
        return this.$message.error(res.msg)
      }
      this.roleList = res.data
    },
    async getAssignRoleList () {
      let temp = []
      let roleList = this.$store.state.user.roleList
      roleList.forEach(it => {
        temp.push(it.id)
      })
      var params = qs.stringify({
        'roleId': temp
      }, { arrayFormat: 'repeat' })
      const { data: res } = await this.$interface.um.getAssignRoleList(params)
      if (res.code !== 0) {
        return this.$message.error(res.msg)
      }
      this.assignRoleList = res.data
    },
    clearFormData () {
      this.clonewidget = false
      this.$refs['newReportDataForm'].resetFields()
      if (this.$refs['dataForm']) this.$refs['dataForm'].resetFields()
      this.dataForm = {
        id: null,
        name: null,
        businessId: getUUID(),
        businessType: null,
        type: 1,
        description: null,
        tenantCode: this.$store.state.user.tenantCode,
        status: null,
        roleIdList: [],
        integration: [],
        po: '',
        da: '',
        jiraNumber: ''
      }
    }
  }
}
</script>

<style lang="scss">
// .add_new_report{
.add_new_report.el-dialog__wrapper {
  background: rgba(0, 0, 0, 0.2);
  .el-dialog {
    background-image: url("#{$--ossLink}/app/other/add_report_bg.png");
    background-position: center;
    background-repeat: no-repeat;
    background-size: 100% 100%;
  }
}
.report_intor {
  word-break: normal;
  line-height: 1.5em;
}
.el-form-item {
  margin-bottom: 10px;
}
.el-form--label-top .el-form-item__label {
  padding: 0px !important;
}
.el-form-item__label {
  margin-bottom: -5px !important;
}
.more-edit-dialog {
  .el-row {
    margin: 0 !important;
  }
  .el-col {
    padding: 0 !important;
  }
}
.right-margin {
  margin-left: 20px !important;
}
// }
</style>
